package net.m510.autosurfer.common;

import java.io.File;
import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class ExternalContentsManager {
	private static final Map<String, String> pathAttr = new HashMap<String, String>();
	static {
		pathAttr.put("img", "src");
		pathAttr.put("link", "href");
		pathAttr.put("script", "src");
	}
	
	public static Document rewriteContentPath(Document doc, String dirName) {
		Elements elems = selectExternalContents(doc);
		for (Element e : elems) {
			String tagname = pathAttr.get(e.tagName());
			String filename = e.attr(tagname);
			File f = new File(dirName,new File(filename).getName());
			e.attr(tagname,f.getPath());
		}
		
		return doc;
	}
	
	public static Elements selectExternalContents( Document doc ) {
		Elements elems = new Elements();
		for (Entry<String, String> e : pathAttr.entrySet() ) {
			String tagname = e.getKey();
			StringBuffer selstr = new StringBuffer("[").append(e.getValue()).append("]");
			elems.addAll(doc.getElementsByTag(tagname).select(selstr.toString()));
		}
		return elems;
	}
	
	public static Set<String> getFileNames(Elements elements) {
		Set<String> files = new HashSet<String>();
		for (Element e : elements) {
			files.add(getFileName(e));
		}
		return files;
	}

	public static Set<String> asUriSet(Elements elements, URI baseUri) {
		Set<String> uriset = new HashSet<String>();
		for (Element e : elements) {
			e.setBaseUri(baseUri.toString());
			uriset.add(e.absUrl(pathAttr.get(e.tagName())));
		}
		return uriset;
	}

	private static String getFileName(Element e) {
		return e.attr(pathAttr.get(e.tagName()));
	}

}
